// Copyright 2009 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Jeff Stewart
// This is the third screen the user sees.  It identifies faults in the chosen
// mail reader configuration and forces the user to fix them before proceeding.
#include <QtGui/QGridLayout>
#include <QtGui/QLabel>

#include "ui/configfixscreen.h"
#include "util/provider.h"

namespace popdiag {

ConfigFixScreen::ConfigFixScreen(QWidget *app)
    : QWizardPage(app),
      fault_display_(new Browser(this, QSize(600, 500))),
      program_name_(new QLabel(this)),
      profile_name_(new QLabel(this)),
      profile_name_label_(new QLabel(this)),
      retest_button_(new QPushButton(this)),
      complete_(true), config_(NULL) {
}

ConfigFixScreen::~ConfigFixScreen() {
}

void ConfigFixScreen::SetupUI() {
  QGridLayout *layout = new QGridLayout(this);
  QString banner = "<h1>";
  banner.append(tr("Step 1/2: Results",
                   "The second step of the wizard"));
  banner.append("</h1><p></p>");
  QLabel *bannerlabel = new QLabel(this);
  bannerlabel->setText(banner);
  bannerlabel->setWordWrap(true);
  layout->addWidget(bannerlabel, 0, 0, 1, 2);

  QLabel *program_name_label = new QLabel(this);
  program_name_label->setText(tr("Email software",
                                 "Label for program selection"));
  layout->addWidget(program_name_label, 1, 0, Qt::AlignTrailing);
  layout->addWidget(program_name_, 1, 1, Qt::AlignLeading);

  layout->addWidget(profile_name_label_, 2, 0, Qt::AlignTrailing);
  layout->addWidget(profile_name_, 2, 1, Qt::AlignLeading);

  layout->addWidget(fault_display_, 3, 0, 1, 2);
  retest_button_->setText(tr("&Retest",
                             "A button label.  Rechecks the program "
                             "configuration"));
  retest_button_->setToolTip(tr("After you fix your client configuration, "
                                "click this button to check the configuration "
                                "again.",
                                "Tooltip for the Retest button"));
  retest_button_->hide();
  QSizePolicy pol = retest_button_->sizePolicy();
  pol.setHorizontalPolicy(QSizePolicy::Maximum);
  retest_button_->setSizePolicy(pol);

  layout->addWidget(retest_button_, 4, 0, 1, 2,
                    Qt::AlignHCenter | Qt::AlignTop);
  CHECK(connect(retest_button_, SIGNAL(clicked(bool)),
                this, SLOT(Retest())));
}

bool ConfigFixScreen::isComplete() const {
  return QWizardPage::isComplete() && complete_;
}

void ConfigFixScreen::SetComplete(bool newval) {
  if (newval) {
    retest_button_->hide();
  } else {
    retest_button_->show();
  }
  complete_ = newval;
  emit completeChanged();
}

void ConfigFixScreen::initializePage() {
  Retest();
}

void ConfigFixScreen::cleanupPage() {
  retest_button_->hide();
}

void ConfigFixScreen::Retest() {
  if (config_ != NULL) {
    QString email = field("email").toString();
    config_->Recalculate(email);
    if (config_ != NULL) {
      emit ClientConfigLogs(config_->debug_text());
    } else {
      emit ClientConfigLogs("User chose not to inspect client configuration");
    }

    setField("imapServer", QString("%1").arg(config_->imap_server()));
    setField("popServer", QString("%1").arg(config_->pop_server()));
    setField("smtpServer", QString("%1").arg(config_->smtp_server()));
    setField("smtpPort", QString("%1").arg(config_->smtp_port()));
  }
  DisplayFault();
}

void ConfigFixScreen::OnConfigChosen(VerificationResult *vr) {
  config_ = vr;
  DisplayFault();
}

void ConfigFixScreen::DisplayFault() {
  // TODO: Acknowledge repairs accomplished.
  fault_display_->show();
  QString fault_description;
  if (config_ == NULL) {
    profile_name_label_->setText(tr("Email address",
                                    "Label for email address"));
    program_name_->setText(tr("Other", "A selection indicating the "
                              "user's mail program is not listed"));
    profile_name_->setText(wizard()->field("email").toString());
    fault_description = tr("We did not check your configuration "
                           "because we were not able to identify "
                           "your email software. "
                           "<p>"
                           "We are now going to check the access "
                           "to your account.",
                           "Explains that we cannot validate the "
                           "configuration.");
    SetComplete(true);
  } else {
    program_name_->setText(config_->program_name());
    QString display_label = QString("%1 (%2)").arg(config_->display_email())
                            .arg(config_->display_name());
    profile_name_label_->setText(tr("Account",
                                    "Label for profile selection"));
    profile_name_->setText(display_label);
    const FaultSet &faults = config_->faults();
    if (faults.size() == 0) {
      fault_description = tr("Your configuration looks correct. "
                             "Click next to test access to your account.",
                             "Explains that the configuration check passed. "
                             "Next is the label of a button");
      SetComplete(true);
    } else {
      CHECK_NE(faults.size(), 0);
      fault_description = "<font color='red'>";
      fault_description += tr("We have found problems with these settings:",
                              "Header for a bulleted list of "
                              "configuration faults");
      fault_description += "<ul>";
      for (FaultSet::const_iterator i = faults.begin();
           i != faults.end(); ++i) {
        QString fault_id = IntToString(i->first);
        fault_description += "<li>" + FaultDescription(*i);
        if (provider->HasSupportLinks()) {
          fault_description += " <a href=\"" +
              provider->GetConfigFaultLink(i->first, config_->program_code()) +
              "\">";
          fault_description += tr("Learn more",
                                  "A label for a hyperlink that will open "
                                  "a browser and display additional external "
                                  "help text about this tool.");
          fault_description += "</a>";
        }
      }
      fault_description.append("</ul>");

      fault_description.append(tr("Please fix these problems, "
                                  "then click Retest to check "
                                  "your configuration again.",
                                  "Having found a fault in the client "
                                  "configuration, this text tells the user "
                                  "what to do next. Retest is the label of "
                                  "a button on this screen."));
      fault_description.append("</font>");
      SetComplete(false);
    }
  }
  fault_display_->setHtml(fault_description);
}

}  // namespace popdiag
